package com.zyj.web.controller.tool;

import com.alibaba.fastjson.JSON;
import com.zyj.assets.domain.AssetsInfo;
import com.zyj.common.constant.Constants;
import com.zyj.common.core.controller.BaseController;
import com.zyj.common.core.domain.entity.SysDept;
import com.zyj.common.core.domain.entity.SysUser;
import com.zyj.common.core.page.TableDataInfo;
import com.zyj.common.utils.DateUtils;
import com.zyj.common.utils.ShiroUtils;
import com.zyj.common.utils.StringUtils;
import com.zyj.common.utils.http.HttpUtils;
import com.zyj.framework.shiro.service.SysPasswordService;
import com.zyj.system.service.ISysDeptService;
import com.zyj.system.service.ISysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 飞书 接口
 * 
开通通讯录权限
 开通获取用户手机号的权限
 */
@Controller
@RequestMapping("/feishu")
public class FeiShuController extends BaseController
{
    @Value("${feishu.app_id}")
    private String app_id;

    @Value("${feishu.app_secret}")
    private String app_secret;

    @Value("${feishu.back_url}")
    private String back_url;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysPasswordService passwordService;


    @GetMapping("/getTicketAndSignature")
    @ResponseBody
    public Map getTicketAndSignature()
    {
        return getToken();
    }

    @GetMapping("/getFeishuDepartment")
    @ResponseBody
    public List<Map> getFeishuDepartment()
    {
        return getDepartment();
    }

    //发送消息
    @PostMapping("/sendMsg")
    @ResponseBody
    public int sendMsg(@RequestParam(name = "json") String json)
    {
        new Thread(new Runnable(){
            @Override
            public void run() {
                if(json!=null && !"".equals(json)){
                    Map maps=(Map)JSON.parse(json);
                    String userids = (String)maps.get("userids");
                    userids = "\""+userids+"\"";
                    userids = userids.replaceAll(",", "\",\"");
                    String msg = (String)maps.get("msg");
                    System.out.println("userids:"+userids+"|"+msg);
                    Map tokenman = getToken();
                    String tenant_access_token = (String)tokenman.get("tenant_access_token");
                    String postJson = "{\"user_ids\":["+userids+"],\"msg_type\":\"text\",\"content\":{\"text\":\""+msg+"\"}}";
                    System.out.println("tenant_access_token:"+tenant_access_token);
                    String url = "https://open.feishu.cn/open-apis/message/v4/batch_send/";
                    System.out.println("postJson:"+postJson);
                    String resultStr = HttpUtils.sendPostFeishuByToken(url, tenant_access_token, postJson);
                    System.out.println("resultStr:"+resultStr);
                }
            }
        }).start();
        return 1;
    }



    public Map getToken(){
        Map resultMap = new HashMap<>();
        if(!"".equals(Constants.ticket)){
            System.out.println("缓存");
            resultMap.put("ticket", Constants.ticket);
            resultMap.put("tenant_access_token",Constants.tenant_access_token);
        }else {
            String url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal";
            String json = "{\"app_id\": \"" + app_id + "\",\"app_secret\": \"" + app_secret + "\"}";
            String token = HttpUtils.sendPostFeishu(url, json);
            Map result = (Map) JSON.parse(token);
            int code = (Integer) result.get("code");
            if (code == 0) {
                String tenant_access_token = (String) result.get("tenant_access_token");
                Constants.tenant_access_token = tenant_access_token;
                resultMap.put("tenant_access_token",tenant_access_token);
                //get jsapi_ticket
                String ticketStr = HttpUtils.sendPostFeishuTicket("https://open.feishu.cn/open-apis/jssdk/ticket/get", tenant_access_token);
                System.out.println(ticketStr);
                Map resultticket = (Map) JSON.parse(ticketStr);
                int codeticket = (Integer) resultticket.get("code");
                if (codeticket == 0) {
                    String ticket = (String) ((Map) resultticket.get("data")).get("ticket");
                    System.out.println("获取");
                    Constants.ticket = ticket;
                    resultMap.put("ticket",ticket);
                }
            }
        }
        return resultMap;
    }

    //
    //每60分钟更新组织和用户
    public List<Map> getDepartment(){
        //先处理根组织下的员工
        getPersion("0",0);
        String url = "https://open.feishu.cn/open-apis/contact/v3/departments/0/children";
        String param = "fetch_child=true&page_size=50";
        Map tokenman = getToken();
        String tenant_access_token = (String)tokenman.get("tenant_access_token");
        System.out.println(tenant_access_token);
        List<Map> list = new ArrayList<Map>();
        String json = HttpUtils.sendGetFeishu(url,param,tenant_access_token);
        System.out.println(json);
        Map department = (Map) JSON.parse(json);
        if((Integer)department.get("code")==0){
            Map data = (Map)department.get("data");
            List<Map> l = (List<Map>)data.get("items");
            if(l!=null && !l.isEmpty()){
                for(int i=0;i<l.size();i++){
                    Map map = l.get(i);
                    String name= (String)map.get("name");
                    String open_department_id = (String)map.get("open_department_id");
                    String parent_department_id = (String)map.get("parent_department_id");
                    boolean is_deleted = (Boolean)((Map)map.get("status")).get("is_deleted");
                    int member_count = (Integer)map.get("member_count");
                    String order = (String)map.get("order");
                    System.out.println(name+"|"+open_department_id+"|"+parent_department_id+"|"+is_deleted+"|"+member_count+"|"+order);
                    //处理入库  1,查找是否存在
                    SysDept dept = deptService.selectDeptByExternalId(open_department_id);

                    if(dept==null){//不存在
                        //新增
                        SysDept deptnew = new SysDept();
                        if("0".equals(parent_department_id)){//根架构
                            deptnew.setParentId(0L);
                        }else{//获取父级id
                            SysDept deptP = deptService.selectDeptByExternalId(parent_department_id);
                            if(deptP!=null){
                                deptnew.setParentId(deptP.getDeptId());
                            }else{
                                continue;
                            }
                        }
                        deptnew.setDeptName(name);
                        deptnew.setOrderNum(Integer.parseInt(order));
                        deptnew.setStatus("0");
                        deptnew.setDelFlag("0");
                        deptnew.setCreateBy("admin");
                        deptnew.setCreateTime(new Date());
                        deptnew.setExternalId(open_department_id);
                        deptnew.setPexternalId(parent_department_id);
                        deptService.insertDept(deptnew);
                    }else{
                        dept.setDeptName(name);
                        dept.setPexternalId(parent_department_id);
                        if(is_deleted){
                            dept.setStatus("1");
                            dept.setDelFlag("2");
                        }
                        //更新
                        deptService.updateDept(dept);

                        //获取部门下的员工信息
                        getPersion(open_department_id,dept.getDeptId());
                    }
                }
            }

        }

        return list;
    }

    //获取所有用户
    public List<Map> getPersion(String opendepartmentid,long deptid){
        String url = "https://open.feishu.cn/open-apis/contact/v3/users/find_by_department";
        String param = "department_id="+opendepartmentid;
        Map tokenman = getToken();
        String tenant_access_token = (String)tokenman.get("tenant_access_token");
        List<Map> list = new ArrayList<Map>();
        String json = HttpUtils.sendGetFeishu(url,param,tenant_access_token);
        System.out.println(json);
        Map department = (Map) JSON.parse(json);
        if((Integer)department.get("code")==0){
            Map data = (Map)department.get("data");
            List<Map> l = (List<Map>)data.get("items");
            System.out.println(l);
            if(l!=null && !l.isEmpty()) {
                for (int i = 0; i < l.size(); i++) {
                    Map map = l.get(i);
                    String external_userid = (String)map.get("user_id");
                    String name = (String)map.get("name");
                    String mobile = "";
                    if(map.get("mobile")!=null && !"".equals(map.get("mobile"))) {
                        mobile = ((String) map.get("mobile")).replace("+86","");
                    }
                    String email = (String)map.get("email");
                    String sex = "";
                    if(map.get("gender")!=null) {
                        int gender = (Integer)map.get("gender");
                        if(gender==0){
                            sex = "2";
                        }else if(gender==1){
                            sex = "0";
                        }else if(gender==2){
                            sex = "1";
                        }
                    }
                    String avatar = (String)((Map)map.get("avatar")).get("avatar_240");
                    //查询用户是否存在
                    SysUser sysuser = sysUserService.selectUserByExternalId(external_userid);
                    if(sysuser==null) {//不存在
                        SysUser sysusernew = new SysUser();
                        sysusernew.setDeptId(deptid);
                        sysusernew.setLoginName(mobile);
                        sysusernew.setUserName(name);
                        sysusernew.setEmail(email);
                        sysusernew.setUserType("00");
                        sysusernew.setPhonenumber(mobile);
                        sysusernew.setSex(sex);
                        sysusernew.setAvatar(avatar);
                        sysusernew.setStatus("0");
                        sysusernew.setDelFlag("0");
                        String salt = ShiroUtils.randomSalt();
                        sysusernew.setSalt(salt);
                        sysusernew.setPassword(passwordService.encryptPassword(mobile, mobile, salt));
                        sysusernew.setPwdUpdateDate(DateUtils.getNowDate());
                        sysusernew.setExternalUserid(external_userid);
                        Long[] ps = {4L};
                        sysusernew.setPostIds(ps);
                        Long[] rids = {2L};
                        sysusernew.setRoleIds(rids);
                        sysUserService.insertUser(sysusernew);
                    }else{
                        SysUser sysusernew = new SysUser();
                        sysusernew.setUserId(sysuser.getUserId());
                        sysusernew.setDeptId(deptid);
                        sysusernew.setLoginName(mobile);
                        sysusernew.setUserName(name);
                        sysusernew.setEmail(email);
                        sysusernew.setUserType("00");
                        sysusernew.setPhonenumber(mobile);
                        sysusernew.setSex(sex);
                        sysusernew.setAvatar(avatar);
                        boolean is_resigned = (Boolean)((Map)map.get("status")).get("is_resigned");
                        if(is_resigned){//离职
                            sysusernew.setStatus("1");
                            sysusernew.setDelFlag("2");
                        }
                        sysUserService.updateUserInfo(sysusernew);
                    }
                }
            }

        }

        return list;
    }

    @GetMapping("/login")
    public String login(HttpServletRequest request)
    {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        System.out.println(code+"飞书内"+state);
        //调用获取登录用户身份
        String url= "https://open.feishu.cn/open-apis/authen/v1/access_token";
        Map tokenman = getToken();
        String tenant_access_token = (String)tokenman.get("tenant_access_token");
        String postJson = "{\"grant_type\":\"authorization_code\",\"code\":\""+code+"\"}";
        String resultStr = HttpUtils.sendPostFeishuByToken(url, tenant_access_token, postJson);
        Map department = (Map) JSON.parse(resultStr);
        if((Integer)department.get("code")==0) {
            Map data = (Map) department.get("data");
            String userid = data.get("user_id")+"";
            String mobile = data.get("mobile")+"";
            mobile = mobile.replace("+86","");
            System.out.println("mobile="+mobile);
            System.out.println("userid="+userid);
            //开始登录
            UsernamePasswordToken token = new UsernamePasswordToken(mobile, mobile, true);
            Subject subject = SecurityUtils.getSubject();
            String jumpurl = back_url.replace("/feishu/login", "");
            try
            {
                subject.login(token);
                return redirect(jumpurl);
            }catch(Exception e){
                e.printStackTrace();
                return redirect(jumpurl);

            }
        }
        return "";
    }
}
